<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\ProductArea;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use app\services\Chain;

class Up
{
    protected $order;
    protected $user;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $is_bao = ProductArea::checkBao($product_id);

        // 必须是报单区
        if ($is_bao) {
            $this->upMyself();
        }

    }

    // 升级自己
    protected function upMyself()
    {
        $user = $this->user;

        if ($user->level < UserLevel::$keys['vip1']) {

            // 部计2800下单, 才能升级
            $sum = Order::find()
                ->where(['user_id' => $user->id])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->sum('total_pay');

            $set = SetUserUp::getLastOne();

            $flag = floatval($set->total) <= floatval($sum);

            // var_dump($set->total, $sum, $flag);exit;

            if ($flag) {
                $user->level = UserLevel::$keys['vip1'];
                $user->save();
            }
        }

    }


}